/*
 * SHOPTNT 版权所有。
 * 未经许可，您不得使用此文件。
 * 官方地址：www.shoptnt.cn
 */
package cn.shoptnt.framework;

import cn.shoptnt.framework.context.user.UserContext;
import cn.shoptnt.framework.context.user.UserHolder;
import cn.shoptnt.framework.elasticsearch.core.EsIndexInit;
import cn.shoptnt.framework.util.DbSecretUtil;
import cn.shoptnt.framework.validation.impl.SafeDomainValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * ShopTnt项目启动配置
 *
 * @author 妙贤
 * @version 1.0
 * @since 7.1.0
 * 2019-05-28
 */

@Component
@Order(value = 1)
public class ShopTntAppRunner implements ApplicationRunner {


    /**
     * 用户信息holder，认证信息的获取者
     */
    @Autowired
    private UserHolder userHolder;

    @Autowired
    private ShopTntConfig shoptntConfig;

    @Autowired
    private EsIndexInit esIndexInit;

    /**
     * 获取配置文件中的域名白名单
     */
    @Autowired
    private ShopTntSecurityDomain shoptntSecurityDomain;


    /**
     * 在项目加载时指定认证信息获取者
     * 默认是由spring 安全上下文中获取
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (shoptntConfig.getTokenSecret() == null) {
            String errorMsg = "配置异常:未配置token秘钥，请检查如下：\n";
            errorMsg += "===========================\n";
            errorMsg += "   shoptnt.token-secret\n";
            errorMsg += "===========================";

            throw new Exception(errorMsg);
        }

        UserContext.setHolder(userHolder);

        //设置AES
        DbSecretUtil.isEncryptSetting = shoptntConfig.isEncryptSetting();

        //给安全校验模块设置url域名白名单
        SafeDomainValidator.setUrlWhiteList(shoptntSecurityDomain.getDomain());

        //进行初始化ES索引操作
        esIndexInit.initEs();
    }

}
